package com.utils.gson.adapter;

import com.google.gson.*;

import java.lang.reflect.Type;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class LocalDateAdapter implements JsonSerializer<LocalDate>,JsonDeserializer<LocalDate>{
    @Override
    public JsonElement serialize(LocalDate LocalDate, Type type, JsonSerializationContext jsonSerializationContext) {
        return new JsonPrimitive(LocalDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
    }
    //反序列化
    @Override
    public LocalDate deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
        return LocalDate.parse(jsonElement.getAsJsonPrimitive().getAsString(), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        //下面这个也行，并且当时间带时区时就必须用下面这个
        //return ZonedDateTime.parse(jsonElement.getAsJsonPrimitive().getAsString()).toLocalDateTime();
    }

}